package com.example.study.ipc

import android.os.IBinder
import android.os.Parcel

/**
 * Created by lijinxi on 2024/2/28
 * @Description:
 */
class BookManagerProxy(private val binder: IBinder) : IBookManager {
    companion object {
        private const val DESCRIPTOR = "com.example.study.ipc.IBookManager"
    }

    override fun getBooks(): List<Book?>? {
        val data = Parcel.obtain()
        val reply = Parcel.obtain()
        val result: ArrayList<Book>?
        try {
            data.writeInterfaceToken(DESCRIPTOR)
            binder.transact(BookManagerStub.TRANSAVTION_getBooks, data, reply, 0)
            reply.readException()
            result = reply.createTypedArrayList(Book.CREATOR)
        } finally {
            data.recycle()
            reply.recycle()
        }
        return result
    }

    override fun addBook(book: Book?) {
        val data = Parcel.obtain()
        val replay = Parcel.obtain()

        try {
            data.writeInterfaceToken(DESCRIPTOR)
            if (book != null) {
                data.writeInt(1)
                book.writeToParcel(data, 0)
            } else {
                data.writeInt(0)
            }
            binder.transact(BookManagerStub.TRANSAVTION_addBook, data, replay, 0)
            replay.readException()
        } finally {
            replay.recycle()
            data.recycle()
        }
    }

    override fun asBinder(): IBinder {
        return binder
    }
}